﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;

namespace CmjUpload.Web.Util
{
    public class CmjUpload
    {
        public static void Save(string relationPath)
        {
            string fileName = HttpContext.Current.Request["fileName"];
            Save(relationPath,fileName);
        }

        public static void Save(string relationPath,string outputName)
        {
            string status = HttpContext.Current.Request["status"];
            if (status == "Start")
            {
                using (FileStream fs = File.Create(Path.Combine(relationPath, outputName)))
                {
                    SaveFile(HttpContext.Current.Request.InputStream, fs);
                }
            }
            else if (status == "Uploading")
            {
                using (FileStream fs = File.Open(Path.Combine(relationPath, outputName), FileMode.Append))
                {
                    SaveFile(HttpContext.Current.Request.InputStream, fs);
                }
            }
            else if (status == "Completed")
            {
                HttpContext.Current.Response.Write("{success:true}");
            }
        }

        private static void SaveFile(Stream stream, FileStream fs)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                fs.Write(buffer, 0, bytesRead);
            }
        }
    }
}